<?php
/**
 * Created by PhpStorm.
 * User: spatra
 * Date: 14-10-3
 * Time: 下午6:15
 */

class AuthorityController extends BaseController
{
    public function __construct()
    {
        $this->beforeFilter('csrf', ['on'=>'post']);
    }

	/**
	 * 返回单独的登陆页面
	 */
	public function getSignin()
    {
		echo '建设中(login single page)';
	}

	/**
	 * 校验用户数据，进行登陆操作
	 */
	public function postLogin()
    {
		$password = Input::get('password');
		$identify = Input::get('identify');

		if( Auth::attempt(['email'=>$identify, 'password'=>$password, 'activated'=>1])
			|| Auth::attempt(['username'=>$identify, 'password'=>$password, 'activated'=>1])
		){
			return Redirect::to('/ng#/lesson/list/all');
		}
		else{
			return Redirect::back()->withInput()->withErrors(['loginFailed'=> '登陆失败，账号（电子邮箱地址）或密码错误！']);
		}
	}

	/**
	 * 退出登陆，并返回到首页.
	 *
	 * @return \Illuminate\Http\RedirectResponse
	 */
	public function getLogout()
    {
		Auth::logout();

		return Redirect::to('/');
	}


	/**
	 * 返回注册页面。
	 *
	 * @return $this
	 */
	public function getSignup()
    {
		if( Auth::check() ){
			return Redirect::to('/ng#/lesson/list/all');
		}
		else{
			$roles = Role::all();
			return View::make('auth.signup')->with('roles', $roles);
		}
	}

	/**
	 * 校验用户的注册数据，并进行注册处理.
	 *
	 * @return $this
	 */
	public function postSignup()
    {
		$postData = Input::all();

		$verifiedRules = [
			'email' => 'required|email|unique:users',
			'username' => 'required|unique:users',
			'password' => 'required|alpha_dash|confirmed',
			'role_id' => 'required|alpha_num|exists:roles,id'
		];

		$errorMessages = [
			'email.email' => '这并非是有效的电子邮箱地址！',
			'username.unique' => '所填写的用户名已经被注册了!',
			'email.unique' => '所填写的电子邮件地址已经被注册了！',
			'password.confirmed' => '两次填写的密码不一致！',
			'require' => '这个是必填项，请务必填写！'
		];

		$validator = Validator::make($postData, $verifiedRules, $errorMessages);

		if( $validator->passes() ){

			unset( $postData['password_confirmation'] );
			$postData['password'] = Hash::make( $postData['password'] );

			$add_user = User::create($postData);

			if( $add_user ){
				Auth::login($add_user);
				return Redirect::to('/ng#/personal/info/profile');
			}
			else{
				return Redirect::back()->withInput()->withErrors(['addError'=>'注册失败']);
			}
		}
		else{
			return Redirect::back()->withInput()->withErrors($validator);
		}
	}

}